package com.paw.file.service.impl;

import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.*;
import com.paw.file.config.AliyunOSSProperty;
import com.paw.file.entity.FileInfo;
import com.paw.file.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URL;

/**
 * @author Rubble
 * Created on 2020/4/23
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private AliyunOSSProperty ossProperty;

    @Override
    public void upload(FileInfo fileInfo,InputStream inputStream){
        String endpoint = ossProperty.getEndpoint();
        String accessKeyId = ossProperty.getAccessKeyId();
        String accessKeySecret = ossProperty.getAccessKeySecret();
        String bucketName = ossProperty.getBucketName();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String  objectName = fileInfo.getPath();
        String url = ossProperty.getBucketUrl()+"/"+objectName;
        fileInfo.setUrl(url);
        // <yourObjectName>表示上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName,inputStream);

        // 如果需要上传时设置存储类型与访问权限，请参考以下示例代码。
         ObjectMetadata metadata = new ObjectMetadata();
         metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
         metadata.setObjectAcl(CannedAccessControlList.PublicRead);
        metadata.setHeader(OSSHeaders.CONTENT_TYPE,fileInfo.getContentType());

         putObjectRequest.setMetadata(metadata);

        // 上传字符串。
        ossClient.putObject(putObjectRequest);

        // 关闭OSSClient。
        ossClient.shutdown();
    }


}
